<?php

namespace App\depository;

use App\Enum\ApiLogEnum;
use App\Enum\CommonEnum;
use App\Models\SubApiLogModel;

class SubApiLogDep
{
    public $model;

    public function __construct()
    {
        $this->model = new SubApiLogModel();
    }

    public function firstById($id){
        $res = $this->model->where('id',$id)->first();
        return $res;
    }

    public function list($teamId,$param)
    {
        $res = $this->model
            ->where("team_id",$teamId)
            ->when(!empty($param['title']), function ($query) use ($param) {
                $link = [];
                foreach (ApiLogEnum::$statusArr as $key => $item){
                    if(strpos($item,$param['title']) !== false ){
                        $link[] = $key;
                    }
                }
                return $query->whereIn("path",$link);
            })
            ->when(!empty($param['link']), function ($query) use ($param) {
                return $query->where("path",'like',"%{$param['link']}%");
            })
            ->when(!empty($param['param']), function ($query) use ($param) {
                return $query->where("input",'like',"%{$param['param']}%");
            })
            ->when(!empty($param['ip']), function ($query) use ($param) {
                return $query->where("ip",'like',"%{$param['ip']}%");
            })
            ->when(!empty($param['user']), function ($query) use ($param) {
                $dep = new UserDep();
                $resUser = $dep->firstLikeUsername($param['user']);
                return $query->where("user_id", "{$resUser->id}");
            })
            ->when(!empty($param['created_at'][0]),function($query) use($param){
                return $query->where("created_at",">=",$param['created_at'][0]);
            })
            ->when(!empty($param['created_at'][1]),function($query) use($param){
                return $query->where("created_at","<=",$param['created_at'][1]);
            })
            ->orderBy('id', 'desc')
            ->paginate($param['per_page'], ['*'], 'page', $param['current_page']);;
        return $res;
    }


    public function add($data)
    {
        $res = $this->model->insert($data);
        return $res;
    }

    public function upd($id, $data)
    {
        $res = $this->model->where('id', $id)->update($data);
        return $res;
    }

    public function del($ids)
    {
        $res = $this->model->whereIn('id', $ids)->delete();
        return $res;
    }

}
